<template>
  <div>
    <el-card>
      <div slot="header">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path:homePath}">项目/建筑管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{ titleName }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div>
        <el-form
          label-position="right"
          label-width="80px"
          ref="formRef"
          :model="formData"
          :rules="rules"
        >
          <el-form-item label="项目名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入项目名称"
            ></el-input>
          </el-form-item>
          <!--<el-form-item label="项目别名" prop="displayName">
            <el-input
              v-model="formData.displayName"
              placeholder="请输入项目别名"
            ></el-input>
          </el-form-item>-->
          <el-form-item label="项目描述" prop="description">
            <el-input type="textarea" v-model="formData.description" :rows="2" maxlength="80" placeholder="请输入项目描述" style="width: 100%" />
          </el-form-item>
          <el-form-item label="项目图片">
            <div
              v-for="(item, index) in imgKeys"
              :key="item.imgkey"
              style="float: left; margin-right: 10px"
              class="img-box"
            >
              <div @click="delImg(index)" class="close-icon">
                <i class="el-icon-error"></i>
              </div>
              <img
                :src="item.httpUrl"
                class="uploadImg"
                style="border: 1px solid #ccc; width: 300px; height: 220px"
              />
            </div>
            <el-upload
              class="upload-demo"
              drag
              ref="uploadAdd"
              action
              :http-request="uploadImg"
              :on-success="uploadImgSuccess"
              :on-remove="handleRemove"
              multiple
              show-file-list
            >
              <!-- <div v-else> -->
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
              </div>
              <!-- </div> -->
              <!--<div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过20MB
              </div>-->
            </el-upload>
          </el-form-item>
        </el-form>
        <el-row style="text-align: center">
          <el-button
            type="primary"
            :loading="submitLoading"
            icon="el-icon-check"
            @click="submitForm('formRef')"
            >提 交
          </el-button>
          <el-button icon="el-icon-back" @click="back">返 回</el-button>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script>
import { create, update, get } from "@/api/projectManage";
import { upload, getImg } from "@/api/common";
export default {
  name: "editForm",
  data() {
    return {
      titleName: "",
      formData: {},
      editType: 0, // 0 创建项目，1 编辑项目
      imgKeys: [],
      uploadUrls: [],
      projectId: "",
      submitLoading: false,
      rules: {
        name: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
        /*displayName: [
          { required: true, message: "请输入项目别名", trigger: "blur" },
        ],*/
        description: [{required: true, message: "请输入项目描述", trigger: "blur"}]
      },
      homePath:"/projectManage"
    };
  },
  created() {},
  mounted() {
    this.projectId = this.$route.query.projectId;
      this.page = this.$route.query.page;
    this.search = this.$route.query.search;
    this.homePath = `${this.homePath}?page=${this.page}&search=${this.search}`

    if (this.projectId) {
      this.titleName = "编辑项目";
      this.editType = 1;
      get({ projectId: this.projectId }).then((res) => {
        this.formData = res.value;
        for (let i = 0; i < this.formData.imageKeys.length; i++) {
          const element = this.formData.imageKeys[i];
          this.imgKeys.push({ imgkey: element, httpUrl: "" });
          this.getImgFun(element);
        }
      });
    } else {
      this.titleName = "创建项目";
      this.editType = 0;
    }
  },
  computed: {},
  methods: {
    getImgFun(val) {
      let data = {
        key: val,
      };
      getImg(data).then((res) => {
        for (let i = 0; i < this.imgKeys.length; i++) {
          if (this.imgKeys[i].imgkey == val) {
            this.imgKeys[i].httpUrl = res.value;
          }
        }
      });
    },
    delImg(index) {
      this.imgKeys.splice(index, 1);
    },
    uploadImg(f) {
      let param = new FormData(); //创建form对象
      param.append("file", f.file); //通过append向form对象添加数据
      param.append("type", "PROJECT_PIC"); //添加form表单中其他数据
      upload(param) //上传
        .then((response) => {
          if (response.code == "200") {
            this.imgKeys.push({
              imgkey: response.value.key,
              httpUrl: response.value.url,
            });
            this.$message.success("上传成功!");
            this.close();
          }
        })
        .catch(() => {
          f.onError();
        });
    },
    uploadImgSuccess() {
      // 缓存接口调用所需的文件路径
      console.log("文件上传成功");
      // this.$message.success("上传成功!");
    },
    handleRemove(file, fileList) {
      // 更新缓存文件
      console.log("文件删除");
    },
    back() {
      this.$router.push(this.homePath);
    },
    submitForm(formName) {
      this.submitLoading = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let imageKeys = this.imgKeys.map((item) => {
            return item.imgkey;
          });

          this.formData.imageKeys = imageKeys;
          if (this.projectId == "" || !this.projectId) {
            this.submitLoading = true;
            create(this.formData)
              .then(() => {
                this.submitLoading = false;
                this.back();
              })
              .catch(() => {
                this.submitLoading = false;
              });
          } else {
            this.submitLoading = true;
            update(this.formData)
              .then(() => {
                this.submitLoading = false;
                this.back();
              })
              .catch(() => {
                this.submitLoading = false;
              });
          }
        } else {
          this.submitLoading = false;
          return false;
        }
      });
    },
  },
};
</script>
<style>
.upload-demo .el-upload-dragger{

  border: 1px solid #ccc; width: 300px; height: 220px;
}
.upload-demo .el-upload-dragger .el-icon-upload{
  line-height: 100px;
}
</style>
<style scoped>
.uploadImg {
  width: auto;
  height: 100%;
}
.img-box {
  position: relative;
}
.img-box .close-icon {
  background-color: #fff;
  width: 25px;
  height: 25px;
  line-height: 25px;
  border-radius: 100%;
  font-size: 25px;
  color: #999;
  position: absolute;
  right: 5px;
  top: 1px;
}
</style>
